#ifndef FREYABASEPLUGINEX_H
#define FREYABASEPLUGINEX_H

#include "freyapublicregister.h"
#include "freyabasecontrol.h"
#include "freyalib_global.h"
#include "ftcpsocket.h"

#include <QDateTime>
#include <QTcpServer>
#include <QHostAddress>

class FREYALIBSHARED_EXPORT FreyaBasePluginEx : public QThread
{
    Q_OBJECT
public:
    explicit FreyaBasePluginEx(QHostAddress platformAddr, int port, FreyaBaseControl *pControl, const QString &PluginName = "FreyaBasePluginEx");
    ~FreyaBasePluginEx();
    bool IsPluginConnected();
    int PluginMSGAuth() const;
    int PluginCMDAuth() const;
    QString PluginID() const;

    void ConnectToExtension();
    void DisconnectToExtension();
    bool ImportPluginAuth(const QStringList &MsgCode, const QStringList &CmdCode);

    void NeedNOOP(bool isNeed);
    void NeedProcesslog(bool isNeed, const QString &path);

    bool PluginWrite(const quint64 &command, int msec = 0);
    bool PluginWrite(FreyaData &pData, int msec = 0);

    bool WriteToPusher(const FreyaData pData);

private:
    bool WaitForConnect();
    void Processlog(const QByteArray &data);
    void Processlog(const FreyaData pData);
    bool CheckFilePath(const QString &filePath);

    static void OnPusherQuery(const FreyaData pData, int msec, FreyaBasePluginEx *object, FreyaBaseControl *pControl);

    void AddQueryData(const FreyaData pData, int msec);
    bool CheckSysTime();

signals:
    void ToPluginConnected(bool);
    void ToConnectToExtension();
    void ToPusherReply(FreyaData);

private slots:
    void OnConnectToExtension();
    void OnReadyRead(const QByteArray &byteData);
    void OnPusherConnected();
    void OnDisconnected();
    void OnPluginReadyRead(const QByteArray &byteData);
    void OnPluginReadyRead(QByteArray *pBa, FreyaData pData, bool pBRet);
    void OnPluginWrite(const FreyaData pData);
    void OnPluginWrite(QByteArray *pBa, FreyaData pData, bool pBRet);
    void OnNoopTimeout();

    void OnDelayTimeout();

private:
    QString                     m_PluginId;
    QHostAddress                m_addPlatform;
    int                         m_iPort;
    FTcpSocket                  *m_PluginSocket;
    QTcpServer                  *m_PluginServer;
    FTcpSocket                  *m_Pusher;
    FreyaBaseControl            *m_pControl;
    int                         m_MsgAuth;
    int                         m_CmdAuth;
    QTimer                      m_NoopTimer;
    QFile                       m_bProcesslogFile;

    QHash<QString, FreyaData>   m_hashQueryData;
    QMutex                      m_mutexQuery;
    QTimer                      m_ReplyDelayTimer;
    QMap<QDateTime, QStringList>    m_mapQueryDelay;
};

#endif // FREYABASEPLUGINEX_H
